package com.witframework.plugin.jbossrules.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.witframework.util.Chinese2Spell;
/**
 * 对中文规则进行预处理，是drools具有处理中文dsl的能力
 * 同时对于由于设置了不正确的编码或是在drl或dsl由于存在非法字符引起的编译错误。
 * 增加了drools对中文规则名的处理能力
 * @author wuxinyang
 *
 */
public class ChineseSource {
	private static Logger logger = Logger.getLogger(ChineseSource.class);
	private static ListOrderedMap hm=new ListOrderedMap();
	static {
		hm.put("如果:","when");
		hm.put("如果","when");

		hm.put("那么:","then");
		hm.put("那么","then");

		hm.put("规则:","rule");
		hm.put("规则","rule");

		hm.put("则:","then");
		hm.put("则","then");

		hm.put("结束","end");

		hm.put("并且","And");
		hm.put("且","And");

		hm.put("小于或等于","<=");
		hm.put("大于或等于",">=");

		hm.put("不存在","Not Exists");
		hm.put("不包含","Excludes");
		hm.put("不等于","!=");

		hm.put("不是","!=");
		hm.put("包含","Contains");
		hm.put("等于","==");
		hm.put("小于","<");
		hm.put("或者","Or");
		hm.put("大于",">");
		hm.put("存在","Exists");

		hm.put("不","Not");
		hm.put("是","==");
		hm.put("或","Or");

	}
	public static InputStreamReader convert(InputStream is, boolean convert, String charset)
			throws IOException {
		if (convert) {
			if (charset == null)
				charset = "UTF-8";
			InputStreamReader isr = new InputStreamReader(is, charset);
			StringBuffer s = new StringBuffer();
			char[] buffer = new char[512];
			int len = 0;
			while ((len = isr.read(buffer)) > 0) {
				s.append(new String(buffer, 0, len));
			}
			String rs=s.toString();
			/**
			 * 去掉对关键字的中文识别，主要是考虑到需要提供界面给用户编辑规则
			 *
			 */
			//rs=maping(hm,rs);
			rs=convertRuleName(rs);
			HashMap varMap=cacheStringVar(rs);
			rs=Chinese2Spell.getChineseSpell(rs);
			rs=dealNonAscii(rs);
			rs=maping(varMap,rs);
			logger.debug(rs);
			return new InputStreamReader(new ByteArrayInputStream(rs.getBytes()));
		} else {
			return new InputStreamReader(is);
		}
	}
	private static String convertRuleName(String str){
		Reader in=new InputStreamReader(new ByteArrayInputStream(str.getBytes()));
		LineNumberReader lr=new LineNumberReader(in);
		String line;
		try {
			while((line=lr.readLine())!=null){
				line=line.trim();
				if(line.indexOf("rule")==0||line.indexOf("规则")==0){
					str=StringUtils.replace(str,line,Chinese2Spell.getChineseSpell(line));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	private static HashMap cacheStringVar(String str){
		HashMap strMap=new HashMap();
		int len=str.length();
		int e=0;
		int b=0;
		while((b=str.indexOf("\"",e))>-1&&e>-1){
			if(e>=len||b+1>=len) break;
			e=str.indexOf("\"",b+1)+1;
			if(e>-1){
				String temp=str.substring(b+1,e-1);
				strMap.put("\""+Chinese2Spell.getChineseSpell(temp)+"\"","\""+temp+"\"");
			}

		}
		return strMap;
	}
	private static String maping(Map map,String str){
		Iterator iter = map.keySet().iterator();
		while (iter.hasNext()) {
			String cnkey=(String)iter.next();
			String keyWord = (String) map.get(cnkey);
			str=StringUtils.replace(str,cnkey,keyWord);
		}
		return str;
	}
	private static String dealNonAscii(String sr){
		return sr.replaceAll("[^\\p{ASCII}]","");
	}
}
